<?php
namespace app\admin\controller;
use app\admin\model\Users as UsersModel;
class Users extends Common{
    //会员列表
    public function index(){
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
            $list=db('users')->alias('u')
                ->join(config('database.prefix').'user_level ul','u.level = ul.level_id','left')
                ->join(config('database.prefix').'users ua','ua.id = u.agentid','left')
                ->field('u.*,ul.level_name,ua.username as agentname')
                ->where('u.mobile|u.username','like',"%".$key."%")
                ->order('u.id desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['reg_time'] = date('Y-m-d H:i',$v['reg_time']);
                // $list['data'][$k]['f_cardid'] = "<a href='".$v['f_cardid']."'><img src='".$v['f_cardid']."' /></a>";
                // $list['data'][$k]['s_cardid'] = "<a href='".$v['s_cardid']."'><img src='".$v['s_cardid']."' /></a>";
                if($v['level']==2){
                    $list['data'][$k]['level_name']='<span class="red">'.$v['level_name'].'</span>'; 
                    $list['data'][$k]['agentlv'] =$v['agentlv'].'%';
                    //余额
                    $a_fei=db('channel_order')->where(array('agentid'=>$v['id'],'state'=>2))->sum('fei_agent');
                    $a_cash=db('bill')->where(array('typeid'=>$v['id']))->sum('cash');
                    $list['data'][$k]['balance'] = number_format($a_fei-$a_cash, 2);
                }else{
                    $list['data'][$k]['agentlv'] ='<span class="hui">暂无</span>';
                    //余额                
                    $u_fei=db('channel_order')->where(array('userid'=>$v['id'],'state'=>2))->sum('fei_user');
                    $u_cash=db('bill')->where(array('typeid'=>$v['id']))->sum('cash');
                    $list['data'][$k]['balance'] = number_format($u_fei-$u_cash, 2);
                    // $list['data'][$k]['balance'] = number_format($a_fei-$a_cash, 2);
                }
                if(!$v['agentname']) $list['data'][$k]['agentname'] =$this->system['name'];
                
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }
    // 下级码商
    public function auserlist(){
        if(request()->isPost()){
            $key=input('post.key');
            $agentid=input('post.agentid');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
            $list=db('users')->alias('u')
                ->join(config('database.prefix').'user_level ul','u.level = ul.level_id','left')
                ->join(config('database.prefix').'users ua','ua.id = u.agentid','left')
                ->field('u.*,ul.level_name,ua.username as agentname')->where('u.agentid',$agentid)
                ->where('u.mobile|u.username','like',"%".$key."%")
                ->order('u.id desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['reg_time'] = date('Y-m-d H:i',$v['reg_time']);
                if($v['level']>1){
                    $list['data'][$k]['level_name']='<span class="red">'.$v['level_name'].'</span>'; 
                    $list['data'][$k]['agentlv'] =$v['agentlv'].'%';
                }else{
                    $list['data'][$k]['agentlv'] ='<span class="hui">暂无</span>';
                }
                if(!$v['agentname']) $list['data'][$k]['agentname'] =$this->system['name'];
                
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        $this->assign('agentid',input('agentid')); 
        return $this->fetch();
    }
    //代理码商
    public function agentlist(){
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
            $list=db('users')->alias('u')
                ->join(config('database.prefix').'user_level ul','u.level = ul.level_id','left')
                ->join(config('database.prefix').'users ua','ua.id = u.agentid','left')
                ->field('u.*,ul.level_name,ua.username as agentname')->where('u.level',2)
                ->where('u.mobile|u.username','like',"%".$key."%")
                ->order('u.id desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['reg_time'] = date('Y-m-d H:i',$v['reg_time']);
                if($v['level']>1){
                    $list['data'][$k]['level_name']='<span class="red">'.$v['level_name'].'</span>'; 
                    $list['data'][$k]['agentlv'] =$v['agentlv'].'%';
                }else{
                    $list['data'][$k]['agentlv'] ='<span class="hui">暂无</span>';
                }
                if(!$v['agentname']) $list['data'][$k]['agentname'] =$this->system['name'];
                
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }
    //设置会员状态
    public function usersState(){
        $id=input('post.id');
        $is_lock=input('post.is_lock');
        if(db('users')->where('id='.$id)->update(['is_lock'=>$is_lock])!==false){
            return ['status'=>1,'msg'=>'设置成功!'];
        }else{
            return ['status'=>0,'msg'=>'设置失败!'];
        }
    }
    public function userstrade(){
        $id=input('post.id');
        $state=input('post.state');
        if(db('users')->where('id='.$id)->update(['state'=>$state])!==false){
            db('channel')->where('userid',$id)->update(array('state'=>$state));  
            return ['status'=>1,'msg'=>'设置成功!'];
        }else{
            return ['status'=>0,'msg'=>'设置失败!'];
        }
    }
    public function edit($id=''){
        if(request()->isPost()){
            $user = db('users');
            $data = input('post.');
            $level =explode(':',$data['level']);
            $data['level'] = $level[1]; 
            if(empty($data['password'])){
                unset($data['password']);
            }else{
                $data['password'] = md5($data['password']);
            }
            if(empty($data['paypwd'])){
                unset($data['paypwd']);
            }else{
                $data['paypwd'] = md5($data['paypwd']);
            }
            if(empty($data['file'])){
                unset($data['file']);
            }
            if(empty($data['f_cardid'])) {
                unset($data['f_cardid']);
            }
            if(empty($data['s_cardid'])) {
                unset($data['s_cardid']);
            }
            if ($user->update($data)!==false) {
                db('channel')->where('userid',$data['id'])->update(array('rate'=>$data['userlv']));  
                $result['msg'] = '修改成功!';
                $result['url'] = url('index');
                $result['code'] = 1;
            } else {
                $result['msg'] = '修改失败!';
                $result['code'] = 0;
            }
            return $result;
        }else{ 
            $user_level=db('user_level')->order('sort')->select();
            $info = UsersModel::get($id);
            $this->assign('info',json_encode($info,true));
            $this->assign('uinfo',$info);
            $this->assign('title',lang('edit').lang('user')); 
            $this->assign('user_level',json_encode($user_level,true)); 
            return $this->fetch();
        }
    }

    public function add($id=''){
        if(request()->isPost()){
            $user = db('users');
            $data = input('post.');

            $level =explode(':',$data['level']);
            $data['level'] = $level[1];  
            $data['password'] = md5($data['password']);
            
            $is_validated = 0 ; 
            $is_validated_e = 0 ; 
            if(is_mobile_phone($data['mobile'])){
                $is_validated = 1;
                $data['mobile_validated'] = 1; 
                if(get_user_info($data['mobile'],2)) return array('code'=>-1,'msg'=>'手机账号已存在');
            }
            if(is_email($data['email'])){
                $is_validated_e = 1; 
                if(get_user_info($data['email'],1)) return array('code'=>-1,'msg'=>'邮箱已存在');
            }
            if($is_validated != 1) return array('code'=>0,'msg'=>'请用手机号注册');
            if($is_validated_e != 1) return array('code'=>0,'msg'=>'请输入正确的邮箱');
            $data['reg_time'] = time(); 
            $data['appid'] = rand_string(8,1);
            $data['appkey'] = rand_string(24,5);
            if(empty($data['file'])){
                unset($data['file']);
            }
            if(empty($data['f_cardid'])){
                $this->error('请上传身份证正面！','index');
            }elseif (empty($data['s_cardid'])) {
                $this->error('请上传身份证反面！','index');
            }
            if(empty($data['paypwd'])){
                $data['paypwd'] = md5('123456');
            }else{
                $data['paypwd'] = md5($data['paypwd']);
            }
            $id = db('users')->insertGetId($data);
            if ($id) {
                $result['msg'] = '新增成功!'; 
                $result['code'] = 1;
            } else {
                $result['msg'] = '新增成功!';
                $result['code'] = 0;
            }
            return $result;
        }else{ 
            $user_level=db('user_level')->order('sort')->select(); 
            $this->assign('title','新增'.lang('user')); 
            $this->assign('user_level',json_encode($user_level,true)); 
            return $this->fetch();
        }
    }

    public function getRegion(){
        $Region=db("region");
        $pid = input("pid");
        $arr = explode(':',$pid);
        $map['pid']=$arr[1];
        $list=$Region->where($map)->select();
        return $list;
    }

    public function usersDel(){
        db('users')->delete(['id'=>input('id')]); 
        return $result = ['code'=>1,'msg'=>'删除成功!'];
    } 

    /***********************************会员组***********************************/
    public function userGroup(){
        if(request()->isPost()){
            $userLevel=db('user_level');
            $list=$userLevel->order('sort')->select();
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list,'rel'=>1];
        }
        return $this->fetch();
    }
    public function groupAdd(){
        if(request()->isPost()){
            $data = input('post.');
            db('user_level')->insert($data);
            $result['msg'] = '添加成功!';
            $result['url'] = url('userGroup');
            $result['code'] = 1;
            return $result;
        }else{
            $this->assign('title',lang('add').lang('user').lang('level'));
            $this->assign('info','null');
            return $this->fetch('groupForm');
        }
    }
    public function groupEdit(){
        if(request()->isPost()) {
            $data = input('post.');
            db('user_level')->update($data);
            $result['msg'] = '修改成功!';
            $result['url'] = url('userGroup');
            $result['code'] = 1;
            return $result;
        }else{
            $map['level_id'] = input('param.level_id');
            $info = db('user_level')->where($map)->find();
            $this->assign('title',lang('edit').lang('user').lang('level'));
            $this->assign('info',json_encode($info,true));
            return $this->fetch('groupForm');
        }
    }
    public function groupDel(){
        $level_id=input('level_id');
        if (empty($level_id)){
            return ['code'=>0,'msg'=>'ID不存在！'];
        }
        db('user_level')->where(array('level_id'=>$level_id))->delete();
        return ['code'=>1,'msg'=>'删除成功！'];
    }
    public function groupOrder(){
        $userLevel=db('user_level');
        $data = input('post.');
        $userLevel->update($data);
        $result['msg'] = '排序更新成功!';
        $result['url'] = url('userGroup');
        $result['code'] = 1;
        return $result;
    }




}